package test;
class BankAccount {
    private double balance;

    // 构造函数，初始化账户余额
    public BankAccount(double balance) {
        this.balance = balance;
    }

    // 取款方法
    public synchronized void withdraw(double amount,String user) {
        // 判断余额是否足够
        if (balance >= amount) {
            // 模拟取款延迟
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            balance -= amount;
            System.out.println(user+" 成功取出：" + amount + "元，当前余额：" + balance + "元");
        } else {
            System.out.println("余额不足，取款失败");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建银行账户，初始余额为2000元
        BankAccount account = new BankAccount(2000);

        // 创建两个用户
        Thread user1 = new Thread(() -> {
            String user = "用户1";
            // 用户1四次分别取100元
            account.withdraw(100,user);
            account.withdraw(100,user);
            account.withdraw(100,user);
            account.withdraw(100,user);
        });

        Thread user2 = new Thread(() -> {
            String user = "用户2";
            // 用户2四次分别取100元
            account.withdraw(100,user);
            account.withdraw(100,user);
            account.withdraw(100,user);
            account.withdraw(100,user);
        });

        // 启动两个线程
        user1.start();
        user2.start();
    }
}